package org.springblade.modules.system.service.impl.idcardauth;

import cn.hutool.json.JSONUtil;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springblade.modules.system.pojo.dto.idcardauth.AliIdCardAuthResponse;
import org.springblade.modules.system.service.IdCardAuthService;
import org.springblade.modules.system.utils.HttpUtils;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @description: 阿里身份实名认证impl
 * @author: luoyt
 * @create: 2024-08-13 22:34
 **/
@Service
@Slf4j
public class AliIdCardAuthServiceImpl implements IdCardAuthService {

    private static final String TAG = "阿里身份实名认证impl";

//    private static final String HOST = "https://lhidcardck.market.alicloudapi.com";
//    private static final String PATH = "/idcard/check";
      private static final String HOST = "https://kzidcardv1.market.alicloudapi.com";
      private static final String PATH = "/api-mall/api/id_card/check";
    private static final String METHOD = "POST";

    private static final String APP_CODE = "8cf6d38dd62643f9b29f18455b04b165";

    @Override
    public boolean authenticate(String name, String idNumber) {

        // 构建请求
        Map<String, String> headers = Maps.newHashMap();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + APP_CODE);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = Maps.newHashMap();
        Map<String, String> bodys = Maps.newHashMap();
        bodys.put("name", name);
        bodys.put("idcard", idNumber);

        try {
            // 发起请求
            HttpResponse response = HttpUtils.doPost(HOST, PATH, METHOD, headers, querys, bodys);
            String respBody = EntityUtils.toString(response.getEntity());
            log.info("{}-原始响应体:{}" , TAG, respBody);

            // 解析响应
            AliIdCardAuthResponse authResponse = JSONUtil.toBean(respBody, AliIdCardAuthResponse.class);

            if (authResponse.isSuccess()) {
                // 处理成功响应
                AliIdCardAuthResponse.AuthData data = authResponse.getData();
                if (data.getResult() == 0) {
                    // 身份信息一致
                    return true;
                } else {
                    // 处理不一致的情况
                    log.info("{}-实名认证不一致：{}", TAG, data.getDesc());
                    return false;
                }
            } else {
                // 处理失败响应
                log.info("{}-认证失败：{}", TAG, authResponse.getMsg());
                System.out.println("认证失败: " + authResponse.getMsg());
                return false;
            }
        } catch (Exception e) {
            log.info("{}-认证异常：{}", TAG, e.getMessage(), e);
            return false;
        }
    }
}